import { getToken, setToken, removeToken } from '@/utils/auth'
import { getInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 存储路由表(默认设置静态路由，已经在router/index.js中设置并导出)
}

const mutations = {
  // 设置token
  setUserToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 移除token
  removeUserToken(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    // newRoutes 动态路由
    // 别忘了解构: 静态路由+动态路由
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  // 获取token并提交存储
  async login(context, payload) {
    // console.log(payload)
    const data = await login(payload)
    context.commit('setUserToken', data)
  },
  // 获取用户信息并提交存储
  async getUserInfo(context) {
    // 1. 发送请求获取用户信息
    const data = await getInfo()
    // 2. 将用户信息保存到vuex中
    context.commit('setUserInfo', data)
    return data
  },
  // 退出登录
  logout(context) {
    context.commit('removeUserToken')
    context.commit('setUserInfo', {})
    resetRouter() // 重置路由
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
